Skip to content

Debug-optional-with-bearer-token#351

Merged
sker65 merged 6 commits intomainfrom
debug-optional-with-bearer-token
Jan 23, 2026
Merged

Debug-optional-with-bearer-token#351
sker65 merged 6 commits intomainfrom
debug-optional-with-bearer-token

Conversation

@sker65
Copy link
Contributor

@sker65 sker65 commented Jan 23, 2026

Summary by CodeRabbit

  • New Features

    • Bearer token authentication added as an alternative to API key for debug and remote fetch flows (config, code, environments).
  • Documentation

    • README and debug command help expanded to document the new bearer token option.
  • Chores

    • Version bumped to 4.5.0.
    • Added a typecheck script for TypeScript validation.
    • Logger default log level made configurable via environment.
  • Tests

    • Added tests for API-key and bearer-token paths, error cases, and logger behavior.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Jan 23, 2026

📝 Walkthrough

Walkthrough

Adds optional bearer-token authentication across CLI and API utilities: new CLI flag, extended option types, direct fetch bearer endpoints in tools (environments, playwright, test-cases), logger log-level helper, package version bump to 4.5.0, and tests covering both API-key and bearer-token flows.

Changes

Cohort / File(s) Summary
Documentation & Versioning
README.md, package.json
Bump version 4.4.0 → 4.5.0; README documents bearer-token auth; added typecheck script.
CLI Interface
src/cli.ts
Added -b, --bearer-token [token] option to debug command and updated command description to mention bearer-token authentication.
Core Options
src/debugtopus/index.ts
Added bearerToken?: string to DebugtopusOptions and propagated it through API/config calls.
Logger
src/logger.ts
Added getLogLevel(level, defaultLevel) and use of env LOG_LEVEL to set logger lowest level (default warning).
API Utilities — Environments
src/tools/environments.ts
GetEnvironmentsOptions accepts bearerToken?; new direct fetch path to BASE_URL/bearer/v1/.../environments with Authorization: Bearer header when bearer token provided.
API Utilities — Playwright
src/tools/playwright.ts
getPlaywrightConfig and getPlaywrightCode accept bearerToken?; added fetch-based bearer-token flows (Authorization header), logging of bearer usage, and PlaywrightCodeResponse type.
API Utilities — Test Cases
src/tools/test-cases.ts
GetTestCasesOptions accepts bearerToken?; added fetch-based bearer-token flow to retrieve test cases from BASE_URL with Authorization: Bearer.
Tests — Environments
tests/tools/environments.spec.ts
New tests covering API-key and bearer-token paths, success and error cases, and ensuring client.GET is not used for bearer path.
Tests — Playwright
tests/tools/playwright.spec.ts
New tests for getPlaywrightConfig and getPlaywrightCode validating API-key and bearer-token flows, parsing, and error handling.
Tests — Logger
tests/logger.spec.ts
New tests for getLogLevel covering valid/invalid inputs, case-insensitivity, and default overrides.

Sequence Diagram(s)

sequenceDiagram
    participant CLI as CLI
    participant Debugtopus as Debugtopus
    participant Tools as Tools (playwright/environments/test-cases)
    participant Client as API Client
    participant Service as Backend Service

    alt Bearer token provided
        CLI->>Debugtopus: run debug with --bearer-token
        Debugtopus->>Tools: call getPlaywrightConfig/getPlaywrightCode (bearerToken)
        Tools->>Service: fetch BASE_URL/bearer/... with Authorization: Bearer <token>
        Service-->>Tools: bearer response (text/json)
        Tools-->>Debugtopus: return parsed config/code
    else API key path
        CLI->>Debugtopus: run debug without bearer token
        Debugtopus->>Tools: call getPlaywrightConfig/getPlaywrightCode (apiKey)
        Tools->>Client: client.GET /apiKey/v3/...
        Client->>Service: request with apiKey
        Service-->>Client: API response
        Client-->>Tools: return parsed response
        Tools-->>Debugtopus: return config/code
    end
    Debugtopus-->>CLI: config/code available
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested reviewers

  • fabianhinz
  • Germandrummer92

Poem

🐰 I hopped through flags and tokens new,
I carried Bearer where keys once flew,
Tests and CLI now twine in cheer,
Version four-point-five draws near—🥕
A tiny hop to make things clear.

🚥 Pre-merge checks | ✅ 2
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding bearer token as an optional authentication method for the debug command, which is implemented across multiple files.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@src/tools/test-cases.ts`:
- Around line 129-143: The bearer-token branch for fetching test cases omits the
filter query that the API-key path includes; update the code inside the if
(options.bearerToken) block to append the same JSON-encoded query parameter used
by the API-key path (include options.status and options.runStatus) to the
request URL (keep using BASE_URL and options.testTargetId) before calling fetch,
and preserve the Authorization: `Bearer ${options.bearerToken}` header so the
endpoint receives the identical filter structure as in the API-key path.
🧹 Nitpick comments (5)
src/logger.ts (1)

54-58: Consider validating LOG_LEVEL environment variable.

The cast process.env.LOG_LEVEL as LogLevel accepts any string at runtime. If an invalid log level is provided (e.g., LOG_LEVEL=verbose), the behavior depends on the library's handling of unknown levels.

💡 Suggested validation
+const validLogLevels = ["trace", "debug", "info", "warning", "error", "fatal"] as const;
+const getLogLevel = (): LogLevel => {
+  const level = process.env.LOG_LEVEL;
+  if (level && validLogLevels.includes(level as LogLevel)) {
+    return level as LogLevel;
+  }
+  return "warning";
+};
+
 export const configureLogger = async (): Promise<void> =>
   configure({
     // ...
     loggers: [
       // ...
       {
         category: "octomind",
-        lowestLevel: (process.env.LOG_LEVEL as LogLevel) || "warning",
+        lowestLevel: getLogLevel(),
         sinks: ["console"],
       },
     ],
   });
src/cli.ts (1)

152-155: Note: -b shorthand has different meanings across commands.

The debug command uses -b for --bearer-token, while the execute command (line 174) uses -b for --browser. This is technically valid since they're separate commands, but could cause user confusion.

Consider using a different shorthand (e.g., -B or --bearer-token only without shorthand) for consistency, or document this distinction clearly.

src/tools/test-cases.ts (1)

138-142: Improve error handling for bearer token fetch.

The current error handling only uses res.statusText which may not provide sufficient debugging information. Consider including the response body for non-ok responses.

💡 Suggested improvement
   if (res.ok) {
     const response = await res.json();
     return response;
   }
-  throw new Error(`no test cases found. error: ${res.statusText}`);
+  let errorDetail = res.statusText;
+  try {
+    const errorBody = await res.text();
+    if (errorBody) {
+      errorDetail = `${res.status} ${res.statusText}: ${errorBody}`;
+    }
+  } catch {
+    // Ignore if we can't read the body
+  }
+  throw new Error(`Failed to fetch test cases: ${errorDetail}`);
 }
src/tools/environments.ts (1)

54-57: Add type assertion for consistency with other bearer token paths.

The res.json() call returns an untyped value. For consistency with src/tools/playwright.ts (which uses as PlaywrightCodeResponse), consider adding a type assertion here.

♻️ Suggested improvement
     if (res.ok) {
-      const environments = await res.json();
+      const environments = (await res.json()) as EnvironmentResponse[];
       return environments;
     }
src/tools/playwright.ts (1)

17-29: Redundant conditional spreads for required fields.

url and outputDir are required in the function signature, so the conditional checks options.url && and options.outputDir && are unnecessary. Additionally, if these fields were empty strings (which satisfies the type but is falsy), they would be incorrectly omitted from the query params.

♻️ Suggested improvement
     const params = new URLSearchParams({
       ...(options.environmentId && { environmentId: options.environmentId }),
-      ...(options.url && { url: options.url }),
-      ...(options.outputDir && { outputDir: options.outputDir }),
+      url: options.url,
+      outputDir: options.outputDir,
       ...(options.headless !== undefined && {
         headless: options.headless.toString(),
       }),

@sker65 sker65 merged commit 06cf452 into main Jan 23, 2026
4 checks passed
@sker65 sker65 deleted the debug-optional-with-bearer-token branch January 23, 2026 14:08
@coderabbitai coderabbitai bot mentioned this pull request Jan 26, 2026
@coderabbitai coderabbitai bot mentioned this pull request Feb 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

Comments